package com.firebird.app.fekpsl.ui.activity.sword.community

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import android.view.Window
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import android.widget.ImageView
import android.widget.TextView
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.bean.TestQuestions
import com.firebird.app.fekpsl.socket.TestSocketConnection
import com.socks.library.KLog
import kotlinx.android.synthetic.main.sword_community_arena.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class ArenaActivity:AppCompatActivity(){

    var roomId=""//房间的id
    var connection:TestSocketConnection?=null
    var questions=ArrayList<TestQuestions>()//问题列表
    var user=BmobUser.getCurrentUser(MyUser::class.java)//当前用户
    var index=0//当前题目
    var answer=""//本题答案
    var seatNumber=0//座位号
    var seatUser=HashMap<String,Int>()
    var choseItem:TextView?=null

    var handler=Handler(Handler.Callback {
        when(it.what){
            -1->{
                KLog.d("服务器连接成功")
                var msg="addRoom,$roomId,${user.objectId},${user.username}"
                connection!!.sendMsg(msg)
                btn_preper.isClickable=true
            }
            0->{
                var msg=it.obj.toString()
                KLog.d(msg)
                dataHandling(msg)
            }
            22->{
                questions[index].choices=answer
                connection!!.sendMsg("next,$roomId,$index,${user.objectId},$answer")
            }
            220->{
                linear_wait_pk.visibility=View.GONE
                tv_index.visibility=View.VISIBLE
                startAnswer()
            }
            111->{
                toast("服务器故障，请稍后再试")
                finish()
            }
        }
        false
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
//        requestedOrientation=ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
        setContentView(R.layout.sword_community_arena)
        initData()
    }

    fun initData(){
        roomId=intent.getStringExtra("roomId")
        getAllProblem()
        connection= TestSocketConnection(handler,roomId)
        //连接服务器
        connection!!.connection()
        btn_preper.isClickable=false
        btn_preper.setOnClickListener {
            //准备
            var msg="prepare,$roomId,${user.objectId}"
            connection!!.sendMsg(msg)
        }
        tv_bottom_name.text=user.username
        DataUtils.showUserImage(this,user.objectId,iv_bottom_header)

        tv_a.setOnClickListener {
            choseEnsure(tv_a)
        }
        tv_b.setOnClickListener {
            choseEnsure(tv_b)
        }
        tv_c.setOnClickListener {
            choseEnsure(tv_c)
        }
        tv_d.setOnClickListener {
            choseEnsure(tv_d)
        }

        btn_cancel_room.setOnClickListener {
            connection!!.sendMsg("clear,$roomId")
            connection!!.close()
            startActivity<MainActivity>()
            //退出时关闭连接
            if(connection!!.keepConnection){
                connection!!.cutOut(roomId,user!!.objectId)
            }
            finish()
        }
    }

    fun choseEnsure(chose:TextView){
        answer=chose.text.toString()
        choseItem=chose
        choseItem!!.setTextColor(resources.getColor(R.color.choseItem))
        if(questions[index].answer==answer){
            choseItem!!.setBackgroundResource(R.drawable.background_chose_right)
        }else{
            choseItem!!.setBackgroundResource(R.drawable.background_chose_error)
        }
        setisClickableFalse()
        handler.sendEmptyMessageDelayed(22, 1000)
    }

    fun getAllProblem(){
        var query=BmobQuery<TestQuestions>()
        query.setLimit(10)
        query.findObjects(object:FindListener<TestQuestions>(){
            override fun done(p0: MutableList<TestQuestions>?, p1: BmobException?) {
                KLog.d(p0!!.size.toString())
                questions.addAll(p0!!)
            }
        })
    }

    /**
     * 服务器返回的数据处理
     */
    fun dataHandling(msg:String){
        var result=msg.split(",")
        if(msg.startsWith("hasAll")){//房间已满
            toast("房间已满")
        }else if(msg.startsWith("next")){//下一题
            index++
            answer=""
            setIsClickableTrue()
            showAnswer()
        }else if(msg.startsWith("finishAll")){//全部结束
            linear_problem.visibility=View.GONE
            linear_result.visibility=View.VISIBLE
            tv_index.text="答题结束，等待结果统计"
            var rightNumber=0
            for (i in 0 until questions.size){
                if(questions[i].choices==(questions[i].answer)){
                    rightNumber++
                }
            }
            var msg="result,$roomId,${user.objectId},${user.username} 答对了 $rightNumber 道题 "
            tv_result.text=msg
            connection!!.sendMsg(msg)
        }else if(msg.startsWith("result")){//结果
            tv_index.text="答题结果统计"
            var msg=""
            for (i in 1 until  result.size){
                msg+="\n ${result[i]}"
            }
            msg.replace("\n","\\n")
            tv_result.text=msg
        }else if(msg.startsWith("victory")){//赢了
            //胜利了
            linear_problem.visibility=View.GONE
            linear_result.visibility=View.VISIBLE
            tv_result.text=result[1]
            tv_index.text="恭喜你获得胜利"
            connection!!.stopTimer()
        }else if(msg.startsWith("prompt")){//提哦是
            toast(result[1])
        }else if (msg.startsWith("roomInfo")){
            //返回座位号，固定值0
            seatNumber=Integer.valueOf(result[1])
            seatUser[user.objectId]=seatNumber
        }else if (msg.startsWith("allOfRoom")){//房间内的所有人的数据
            //已加入房间的所有人
            showActor(result)
        }else if (msg.startsWith("newOnRoom")){//新人加入房间
            //新加入房间的成员
            if(user.objectId !=result[1]) {//避免因服务器分发问题导致同一个人出现在房间两个座位上
                seatUser[result[1]]=Integer.valueOf(result[3])
                showActor(result[2], Integer.valueOf(result[3]),result[1],false)
            }
        }else if(msg.startsWith("start")){//开始答题
            linear_preper.visibility=View.GONE
            linear_wait_pk.visibility=View.VISIBLE
            handler.sendEmptyMessageDelayed(220,2000)
        }else if(msg.startsWith("prepare")){//开始答题
            if(user.objectId ==result[1]) {
                iv_bottom_prepare.setImageResource(R.mipmap.ioc_prepare)
                btn_preper.text="等待其他选手准备"
                linear_preper.visibility=View.VISIBLE
                btn_preper.visibility=View.GONE
            }
            var seat = seatUser[result[1]]
            if (seat == null) seat = 0
            prepareSeat(seat)
        }else if(msg.startsWith("outRoom")){
            outRoom(result[1])
        }

    }

    /**
     * 开始答题
     */
    fun startAnswer(){
        linear_problem.visibility=View.VISIBLE
        showAnswer()
    }

    /**
     * 展示题目数据
     */
    fun showAnswer(){
        KLog.d(index.toString())
        if(index<questions.size) {
            tv_index.text="第${index+1}题"
            scale(tv_index)
            choseItem?.let {
                choseItem!!.setTextColor(resources.getColor(R.color.black))
                choseItem!!.setBackgroundResource(R.drawable.sword_community_background_chose_item)
            }
            KLog.d(questions[index].problem)
            tv_problem.text = questions[index].problem
            tv_a.text = questions[index].q1
            tv_b.text = questions[index].q2
            tv_c.text = questions[index].q3
            tv_d.text = questions[index].q4
        }else{
            connection!!.sendMsg("finishAll,$roomId,${user.objectId}")
        }
    }

    /**
     * 设置答案不可选
     */
    fun setisClickableFalse(){
        tv_a.isClickable=false
        tv_b.isClickable=false
        tv_c.isClickable=false
        tv_d.isClickable=false
    }

    /**
     * z设置答案可选
     */
    fun setIsClickableTrue(){
        tv_a.isClickable=true
        tv_b.isClickable=true
        tv_c.isClickable=true
        tv_d.isClickable=true
    }

    /**
     * 动画效果
     */
    fun scale(v: View) {
        val anim = ScaleAnimation(1.0f, 1.5f, 1.0f, 1.5f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f)
        anim.duration = 300
        v.startAnimation(anim)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    /**
     * 遍历房间里的所有人
     */
    fun showActor(usersMap:List<String>){
        for (i in 2 until usersMap.size step 4){
            KLog.d(usersMap[i+3])
            seatUser[usersMap[i]]=Integer.valueOf(usersMap[i+3])
            showActor(usersMap[i+1],seatUser[usersMap[i]]!!,usersMap[i],java.lang.Boolean.valueOf(usersMap[i+2]))
        }
    }

    /**
     * 根据座位号与当前用户的座位号确定每个人在屏幕上的位置
     *          x+2(x-2)
     *  x+1(x-3)        x+3(x-1)
     *             x(当前座位号)
     */
    fun showActor(username:String,seat:Int,userId: String,isprepare:Boolean){
        KLog.d(seatNumber.toString())
        if(seat==seatNumber+1||seat==seatNumber-3){
            showActorInfo(iv_left_header,tv_left_name,userId,username)//left
            if(isprepare){ iv_left_prepare.setImageResource(R.mipmap.ioc_prepare) }
        }else if(seat==seatNumber-1||seat==seatNumber+3){
            showActorInfo(iv_right_header,tv_right_name,userId,username)//right
            if(isprepare){ iv_right_prepare.setImageResource(R.mipmap.ioc_prepare) }
        }else if(seat==seatNumber+2||seat==seatNumber-2){
            showActorInfo(iv_top_header,tv_top_name,userId,username)//top
            if(isprepare){ iv_top_prepare.setImageResource(R.mipmap.ioc_prepare) }
        }
    }

    /**
     * 设置名称以及头像
     */
    fun showActorInfo(imageView: ImageView,tvname:TextView,userId: String,name:String){
        DataUtils.showUserImage(this,userId,imageView)
        tvname.text=name
    }

    /**
     * 根据准备人的座位号确定那个位置举手
     */
    fun prepareSeat(seat:Int){
        if(seat==seatNumber+1||seat==seatNumber-3){
            iv_left_prepare.setImageResource(R.mipmap.ioc_prepare)//left
        }else if(seat==seatNumber-1||seat==seatNumber+3){
            iv_right_prepare.setImageResource(R.mipmap.ioc_prepare)//right
        }else if(seat==seatNumber+2||seat==seatNumber-2){
            iv_top_prepare.setImageResource(R.mipmap.ioc_prepare)//top
        }
    }

    /**
     * 根据退出房间人的id清空对应座位
     */
    fun outRoom(userId: String){
        var seat=seatUser[userId]
        if(seat==seatNumber+1||seat==seatNumber-3){
            clearSeat(iv_left_header,tv_left_name,iv_left_prepare)//left
        }else if(seat==seatNumber-1||seat==seatNumber+3){
            clearSeat(iv_right_header,tv_right_name,iv_right_prepare)//right
        }else if(seat==seatNumber+2||seat==seatNumber-2){
            clearSeat(iv_top_header,tv_top_name,iv_top_prepare)//top
        }
    }

    /**
     * 清空座位
     */
    fun clearSeat(header:ImageView,userName:TextView,prepare:ImageView){
        header.setImageDrawable(null)
        userName.text=""
        prepare.setImageDrawable(null)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            //退出时关闭连接
            if(connection!!.keepConnection){
                connection!!.cutOut(roomId,user!!.objectId)
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}